<template>
    <section class="watchSection">
         <layout :isVertical="true">
            <common-toolbar text="用户管理">
                <!-- <el-button class="btn commonButton" type="default" @click="dialogVisible=true">筛选</el-button> -->
                <!-- <el-button class="btn commonButton" type="default" @click="getShanxuan">筛选</el-button> -->
            </common-toolbar>
                 <el-form :inline="true" :model="filters" class="doneForm topParamsForm"
                             @submit.native.prevent="searchList">
                        <el-form-item  :show-message="false" v-for="" class="company" label="姓名：" ref="fullName">
                            <el-input v-model.trim="filters.fullName" class="input-with-select"  placeholder="单行输入">  <el-button slot="append" icon="el-icon-search" @click="searchList"></el-button></el-input>
                            <!-- <common-input class="checkName input-with-select" v-model="filters.fullName" placeholder="单行输入"
                                          :clearable="true">
                                         
                                          </common-input> -->
                        </el-form-item>
                        <!-- <el-form-item  :show-message="false" v-for="" class="fondName" label="万信号：" ref="loginName">
                            <common-input class="checkName" v-model="filters.loginName" placeholder="单行输入"></common-input>
                        </el-form-item> -->
                        <el-form-item :show-message="false" class="rt">
                            <common-button text="创建用户" @click="addUser" v-if="userInfoForm.userName!='admin'"></common-button>
                            <common-button text="删除用户" @click="deleteUser" v-if="userInfoForm.userName!='admin'"></common-button>
                        </el-form-item>
                    </el-form>
            <layout layout="center"  class="centerSection noScrollSection">
                <el-table
                        ref="singleTable"
                        :data="tableData"
                        highlight-current-row
                        :height="bodyHeight"
                        style="width: 100%"  @selection-change="handleSelectionChange">
                         <el-table-column
      type="selection"
      width="55">
    </el-table-column>
                        <el-table-column
                        label="No."
                        width="50" type="index" :index="indexMethod">
                        </el-table-column>
                        <el-table-column
                        property="userName"
                        label="用户名" show-overflow-tooltip="true">
                        </el-table-column>
                        <el-table-column
                        property="enabled"
                        label="状态">
                        <template slot-scope="scope">
                            {{getEnabled(scope.row.enabled)}}
                        </template>
                        </el-table-column>
                        <el-table-column
                        property="fullName"
                        label="姓名" show-overflow-tooltip="true">
                        </el-table-column>
                        <el-table-column
                        property="telephone" show-overflow-tooltip="true"
                        label="手机">
                        </el-table-column>
                        <el-table-column
                        property="email"
                        label="邮箱" show-overflow-tooltip="true">
                        </el-table-column>
                        <el-table-column
                        property="roleId"
                        label="角色名称" show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            {{getRole(scope.row.roleId)}}
                        </template>
                        </el-table-column>
                         <!-- <el-table-column
                        property="headquartersName"
                        label="所属影院">
                        </el-table-column> -->
                        <el-table-column
                        property="createDate"
                        label="创建时间" width="160">
                        </el-table-column>
                        <el-table-column
                        property="updateDate"
                        label="更改时间" width="160">
                        </el-table-column>
                     <el-table-column label="操作" width="400">
                        <template slot-scope="scope">
                            <el-button
                            size="mini"
                            type= 'warning'
                            class="el-icon-edit"
                            @click="updateUserRole(scope.row, scope.$index)">角色配置</el-button>
                            <el-button
                            size="mini"
                            type= 'warning'
                            @click="updateUser(scope.row, scope.$index)">编辑</el-button>
                            <el-button
                            size="mini"
                            type= 'warning'
                            class="el-icon-edit"
                            @click="disabledUser(scope.row, false)"  :disabled="!scope.row.enabled?true:false">禁用</el-button>
                            <el-button
                            size="mini"
                                    class="el-icon-edit"
                            @click="disabledUser(scope.row, true)" :disabled="scope.row.enabled?true:false">启用</el-button>
                              <el-button type="primary" @click="savePasword(scope.row)" class="el-icon-edit" size="mini">重置密码</el-button>
                        </template>
                </el-table-column>
                    </el-table>
                <div class="paginationDiv">
                    <el-pagination
                            background
                            layout="prev, pager, next"
                            @current-change="handleCurrentChange"
                            :page-size="params.pageSize"
                            :total="total">
                    </el-pagination>
                </div>
            
            </layout>
        </layout>
        <el-dialog class="myDialog" title="用户角色设定" :visible.sync="fileVisible" :close-on-click-modal="false">
            <div class="scrollCon formDiv">
                <div class="tableCon tabConErr">
                    <el-form :model="fileForm" label-width="100px" :rules="ruleForm" ref="fileForm" class="userForm">
                        <!-- <el-form-item  :show-message="false" label="用户名：" class="basicItem" ref="fullName" prop="fullName">
                            <common-input class="checkName percentName" v-model="fileForm.fullName"></common-input>
                        </el-form-item>
                        <el-form-item  :show-message="false" label="部门：" class="basicItem">
                            <el-input class="checkName percentName" v-model="fileForm.department"></el-input>
                        </el-form-item>
                        <el-form-item  :show-message="false" label="职务：" class="basicItem">
                            <el-input class="checkName percentName" v-model="fileForm.business"></el-input>
                        </el-form-item> -->
                        <!-- {{remoteList}} -->
                        <el-form-item  :show-message="false" label="角色：" class="basicItem multipleView" ref="roleIds" prop="roleIds">
                            <el-select v-model="fileForm.roleIds" placeholder="请选择">
                                <el-option
                                v-for="item in remoteList"
                                :key="item.id"
                                :label="getLabel(item)"
                                :value="item.id">
                                </el-option>
                            </el-select>
                            <!-- <common-select
                                    placeholder="请选择"
                                    class="w100"
                                    :data="remoteList"
                                    :multiple="true"
                                    v-model="fileForm.roleIds" -->
                            <!-- ></common-select> -->
                        </el-form-item>
                    </el-form>
                </div>
            </div>
            <div slot="footer" class="dialog-footer diaFoot">
                <common-button text="确定" @click="submitForm('fileForm','1')"></common-button>
            </div>
        </el-dialog>
        <el-dialog class="fixModal myDialog" title="所属全宗" :visible.sync="fileVisibleMove1" :close-on-click-modal="true">
            <div class="scrollCon formDiv">
                <div class="tableCon">
                    <div class="treeTitle up_fondTitle">
                        <el-form :inline="true" :model="leftFondForm" class="topParamsForm superLeftForm">
                            <el-form-item  :show-message="false" class="title" label="" ref="name">
                                <el-select class="checkName" v-model="leftFondForm.id" filterable remote reserve-keyword
                                           placeholder="请输入" :remote-method="remoteMethod" :loading="searchLoading">
                                    <el-option v-for="item in searchOptions" :key="item.value" :label="item.label"
                                               :value="item.value">
                                    </el-option>
                                </el-select>
                                <i class="fa fa-search thisBig" @click="fondClick"></i>
                            </el-form-item>
                        </el-form>
                    </div>
                    <!-- <el-tree node-key="id"
                             :data="treeData"
                             ref="treeku"
                             highlight-current
                             :default-expanded-keys="defaultLeftOpen"
                             :props="defaultProps"
                             v-loading="treeLoading"
                             @node-click="handleNodeClick1"
                             :render-content="renderContent">
                    </el-tree> -->

                    <el-tree node-key="id"
                             class="commonTree"
                             ref="treeku"
                             v-loading="treeLoading"
                             :data="treeData"
                             :props="defaultProps"
                             :default-expanded-keys="defaultLeftOpen"
                             @node-click="handleNodeClick1"
                    >
                    </el-tree>
                </div>
            </div>
            <div slot="footer" class="dialog-footer diaFoot">
                <el-button type="primary" class="defaultBtn" @click="getCheckedNodes1()">确定</el-button>
            </div>
        </el-dialog>

        <el-dialog class="myDialog" :title="user.userId?'编辑用户':'创建用户'" :visible.sync="addUserVisible" :close-on-click-modal="false">
            <div class="scrollCon formDiv">
                <div class="tableCon tabConErr">
                    <el-form :model="user" label-width="120px" :rules="userRules" ref="userForm" class="userForm">
                        <el-form-item  :show-message="false" label="姓名：" class="basicItem" ref="fullName" prop="fullName">
                            <common-input required  v-model="user.fullName"></common-input>
                        </el-form-item>
                        <el-form-item  :show-message="false" label="用户名：" class="basicItem" ref="fullName" prop="userName">
                            <common-input required :readOnly="user.userId"  v-model="user.userName"></common-input>
                        </el-form-item>
                        <!-- <el-form-item   :show-message="false" label="所属全宗：" class="basicItem" prop="fondCode">
                            <common-treeSelect
                                    placeholder="请选择"
                                    :normalizer="normalizer"
                                    :options="fonddata"
                                    :clearable="true"
                                    :searchable="true"
                                    :multiple="false"
                                    v-model="user.fondCode"
                                    @treeselect="treeselect"
                                    @input="treeselectInput"
                                    style="line-height: 40px;margin-top:5px;"
                                    :appendToBody="false"
                            ></common-treeSelect>
                        </el-form-item> -->
                        <!-- <el-form-item  :show-message="false" label="部门：" class="basicItem" prop="fondCode">
                            <common-input v-model="user.department"></common-input>
                        </el-form-item> -->
                        <!-- <el-form-item  :show-message="false" label="职务：" class="basicItem">
                            <common-input  v-model="user.business"></common-input>
                        </el-form-item> -->
                        <!-- <el-form-item  label="移动电话：" class="basicItem">
                            <common-input  errorMessage="请输入正确的电话号码" v-model="user.fixedTelephone"></common-input>
                        </el-form-item> -->
                         <el-form-item  label="手机号码：" class="basicItem">
                            <common-input  errorMessage="请输入正确的电话号码" v-model="user.telephone"></common-input>
                        </el-form-item>
                        <!-- <el-form-item  :show-message="false" label="出生日期：" class="basicItem">
                            <date-input  v-model="user.birthday"></date-input>
                        </el-form-item> -->
                        <el-form-item  :show-message="false" label="邮箱：" class="basicItem">
                            <common-input v-model="user.email"></common-input>
                        </el-form-item>
                        <!-- <el-form-item  :show-message="false" label="通信地址：" class="basicItem">
                            <common-input  v-model="user.mailingAddress"></common-input>
                        </el-form-item> -->
                        <!-- <el-form-item  :show-message="false" label="证件类型：" class="basicItem" prop="credentialsType">
                            <common-select
                                    placeholder="证件类型"
                                    :data="credentialsTypeList"
                                    :defaultProps="{value: 'code',label: 'displayText'}"
                                    v-model="user.credentialsType"
                                    size="small"
                                    :clearable="true"
                                    class="w100"
                                    style="max-width:150px;background: #fff;"
                            ></common-select>
                        </el-form-item> -->
                        <!-- <el-form-item  :show-message="false" label="证件号码：" class="basicItem" prop="credentialsNumber">
                            <common-input  v-model="user.credentialsNumber"></common-input>
                        </el-form-item> -->
                        <el-form-item v-if="!user.userId"  :show-message="false" label="密码：" class="basicItem" prop="password" >
                            <common-input type="password"  v-model="user.password"></common-input>
                        </el-form-item>
                        <el-form-item v-if="!user.userId"  :show-message="false" label="再次输入密码：" class="basicItem" prop="passwordAgain">
                            <common-input type="password"  v-model="user.passwordAgain"></common-input>
                        </el-form-item>
                    </el-form>
                </div>
            </div>
            <div slot="footer" class="dialog-footer diaFoot">
                <common-button text="确定" @click="saveUser()"></common-button>
            </div>
        </el-dialog>
    </section>
</template>

<script lang="ts">
    import Vue from 'vue';
    import Component from 'vue-class-component';
    import Service from './userManagement.service';
    import cookieConfig from '@/utils/getCookie';
    import ApiConfig from '@/api/api-config';
    import {JSEncrypt} from 'jsencrypt';
    import CommonService from '../../services/common.service'

    @Component
    export default class appborrow extends Vue {
        fileVisible: boolean;
        addUserVisible = false;
        bodyHeight: number;
        start: number;
        total = 0;
        page = 1;
        userId: number;
        limit: number;
        a: any = {};
        b: any = {};
        fileForm: any = {};
        ruleForm: any = {};
        openForm: any = {};
        filters: any = {};
        tableData: any = [];
        roleSelect: any = [];
        error: any = {};
        tableParams: any = {};
        title: '';
        fullName: '';
        jobname: '';
        unitname: '';
        loginName: '';
        fileVisibleMove1: boolean;
        isloading: boolean = false;
        aloneTree: any = {};
        treeData: any = [];
        defaultLeftOpen: any = [];
        treeLoading: boolean;
        leftFondForm: any = {};
        searchLoading: boolean;
        searchOptions: any = [];//远程搜索条目
        defaultProps: any = {};
        treeObj: any = {};
        RuestUrl: String;
        archiveAgentCode: String;
        fondCode: String;
        params: any = {};
        operates: any = {};
        columns: any = [];
        remoteList: any = [];
        height:500;
        userInfoForm={};
        formName={}
         multipleSelection= [];
        userRules = {
            userName: [
                {required: true, message: '', trigger: 'blur'}
            ],
            loginName: [
                {required: true, message: '', trigger: 'blur'}
            ],
            fullName: [
                {required: true, message: '', trigger: 'blur'}
            ],
            fondCode: [
                {required: true, message: '', trigger: 'blur'}
            ],
            department: [
                {required: true, message: '', trigger: 'blur'}
            ],
            telephone: [
                {required: true, message: '', trigger: 'blur'}
            ],
            password: [
                {required: true, message: '', trigger: 'blur'}
            ],
            passwordAgain: [
                {required: true, message: '', trigger: 'blur'}
            ],
            seq:[{required: true, message: '', trigger: 'blur'}],
        }
        user = {
            userName: null,
            fullName: null,
            fondCode: null,
            department: null,
            business: null,
            telephone: null,
            birthday: null,
            email: null,
            zipCode: null,
            mailingAddress: null,
            credentialsType: null,
            credentialsNumber: null,
            password: null,
            passwordAgain: null,
            fixedTelephone:null
        }

        credentialsTypeList = [];

        fonddata = [];

        selection = [];

        constructor() {
            super();
            this.bodyHeight = document.documentElement.clientHeight - 225;
            this.fileVisible = false;
            this.fileForm = {
                roleIds: [],
                userId: '',
                fondsName: '',
                fondsId: '',
                business: '',
            };
            this.openForm = {};
            this.a = {
                roleIds: [],
                userId: '',
                fondsId: 0,
            };
            this.aloneTree = {name: ''};
            this.treeData = [];
            this.defaultLeftOpen = [];
            this.treeLoading = false;
            this.searchLoading = false;
            this.searchOptions = [];
            this.defaultProps = {
                children: 'children',
                label: 'fondName',
                id: 'id'
            };
            this.b = {
                fullName: '',
                loginName: '',
                page: 1,
                pageSize: 10
            };
            this.params = {
                fullName: '',
                loginName: '',
                page: 1,
                pageSize: 30
            };
            this.fileVisibleMove1 = false;
            this.limit = 10;
            this.filters = {
                loginName: '',
                fullName: '',
                fondsName: '',
            };
            this.ruleForm = {
                jobname: [
                    {required: true, message: '', trigger: 'blur'}
                ],
                unitname: [
                    {required: true, message: '', trigger: 'blur'}
                ],
                loginName: [
                    {required: true, message: '', trigger: 'blur'}
                ],
                roleName: [
                    {required: true, message: '', trigger: 'blur'}
                ],
                roleIds: [
                    {required: true, message: '', trigger: 'change'}
                ],
                fullName: [
                    {required: true, message: '', trigger: 'blur'}
                ],
                fondsName: [
                    {required: true, message: '', trigger: ['blur', 'change']}
                ],
                seq:[{required: true, message: '', trigger: 'blur'}]
            };

            this.tableData = [];
            this.roleSelect = [];
            this.tableParams = {
                userId: '',
                roleIds: '',
            };
            this.treeObj = {};
            this.operates = {
                width: 240,
                fixed: 'right',
                align: 'right',
                list: [
                    {
                        id: '1',
                        label: '角色配置',
                        type: 'warning',
                        showBtn: true,
                        icon: 'el-icon-edit',
                        plain: true,
                        disabled: false,
                        method: (row, index) => {
                            this.updateUserRole(row, index)
                        }
                    },
                    {
                        id: '2',
                        label: '编辑',
                        type: 'warning',
                        showBtn: true,
                        icon: 'el-icon-edit',
                        plain: true,
                        disabled: false,
                        method: (row, index) => {
                            this.updateUser(row)
                        }
                    },
                     {
                        id: '3',
                        label: '禁用',
                        type: 'warning',
                        showBtn: true,
                        icon: 'el-icon-edit',
                        plain: true,
                        disabled: false,
                        method: (row, index) => {
                            this.disabledUser(row,false)
                        }
                    },
                    {
                        id: '4',
                        label: '启用',
                        type: 'warning',
                        showBtn: true,
                        icon: 'el-icon-edit',
                        plain: true,
                        disabled: false,
                        method: (row, index) => {
                            this.disabledUser(row,true)
                        }
                    },
                ]
            }
            this.columns = [
                {
                    title: "序号",
                    field: "seq",
                }, {
                    title: "用户名",
                    field: "userName",
                },
                {
                    title: "状态",
                    field: "enabled",
                }, {
                    title: "姓名",
                    field: "fullName",
                },
                 {
                    title: "手机",
                    field: "telephone",
                },
                {
                    title: "邮箱",
                    field: "email",
                }, {
                    title: "角色名称",
                    field: "roleId",
                },{
                    title: "所属影院",
                    field: "headquartersName",
                }, {
                    title: "创建时间",
                    field: "createDate",
                }, {
                    title: "更改时间",
                    field: "updateDate",
                },
            ]// 需要展示的列
            this.remoteList = [];

        };
        getLabel(item) {
            if(item.roleName!=null&&item.headquartersName!=null) {
                return item.headquartersName+'-'+item.roleName
            } else if(item.headquartersName==null&&item.roleName==null) {
                return item.roleName
            } else if(item.roleName==null&&item.headquartersName!=null) {
                return item.headquartersName
            } else {
                return;
            }
        }
         // 序号
        indexMethod(index) {
        return (this.params.page - 1) * this.params.pageSize + index + 1;
        }
        handleCurrentChange(val) {
            this.params.page = val;
            this.getFiles();
        };

        addUser() {
            this.user = {};
            this.addUserVisible = true;
        }
        getRole(row) {
            for(let item of this.remoteList) {
                if(item.id == row) {
                    return item.roleName
                }
            }
        }
        handleSelectionChange(val) {
            this.selection = val;
        }
        getEnabled(row) {
            if(row) {
                return '正常'
            } else {
                return '禁用'
            }
        }
         savePasword(row) {
            Service.resetPwd({userName:row.userName}).then(res=>{
                if(res.data.succeeded) {
                        this['$message']({
                        message: '重置密码成功',
                        type: 'success'
                    });
                }else {
                    this['$message']({
                        message: res.data.errorMessage,
                        type: 'error'
                    });
                }
            })
        }
        updateUser(row) {
            this.user = {};
            this.user = JSON.parse(JSON.stringify(row));
            this.user.credentialsType = this.user.credentialsType ? '' + this.user.credentialsType : null;
            this.addUserVisible = true;
        }
        // 用户启动禁用
        disabledUser(row,disble) {
              this['$confirm'](disble==true?'确认用户启用吗？':'确认用户禁用吗？', {
                type: 'warning'
            }).then(() => {
                //console.log(this.selection)
                let params = {
                    userId:row.userId,
                    disabled:disble
                }
                Service.disabled(params).then((res) => {
                        if (res.data.succeeded) {
                            this['$message']({
                                message: '保存成功！',
                                type: 'success'
                            });
                            this.getFiles();
                            this.addUserVisible = false;
                        } else {
                            this['$message']({
                                message: res.data.errorMessage,
                                type: 'error'
                            });
                            return;
                        }
                    })
            });
        };
        deleteUser(){
            if(this.selection.length==0) {
                return  this['$confirm']('请选择用户', {
                    type: 'warning'
                }).then(() => {
               
                })
            }
            this['$confirm']('确认删除选中用户吗？', {
                type: 'warning'
            }).then(() => {
                //console.log(this.selection)
                // this.tableData = [];
                let userIds = []
                if(this.selection.length>0) {
                    for(let item of this.selection) {
                        userIds.push(item.userId)
                    }
                }
                let params = {
                    userIds:userIds
                }
                Service.userInfoGetTree(params).then((res) => {
                        if (res.data.succeeded) {
                            this['$message']({
                                message: '保存成功！',
                                type: 'success'
                            });
                            this.getFiles();
                            this.addUserVisible = false;
                        } else {
                            this['$message']({
                                message: res.data.errorMessage,
                                type: 'error'
                            });
                            return;
                        }
                    })
            });
        }

        saveUser(isUpdateRole) {
            const me = this;
            //console.log(isUpdateRole,this.user.email,me.user.telephone)
            if(this.user &&(me.user.telephone != ''&&me.user.telephone !=undefined)) {
                const phoneRege = /^(1[3|4|5|6|7|8|9])\d{9}$|^0\d{2,3}-?\d{7,8}$/;
                let res = phoneRege.test(me.user.telephone)
                if(res == false) {
                     me['$message']({
                        message: '请输入有效的手机号',
                        type: 'warning'
                    });
                return;
                }
            }
            if(this.user &&(me.user.email != ''&&me.user.email !=undefined)) {
                // debugger
                const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
                let res= re.test(me.user.email)
                //  //console.log(re.test(me.user.email),res)
                if(res == false) {
                     me['$message']({
                        message: '请输入有效的邮箱',
                        type: 'warning'
                    });
                    return ;
                }
            }
            if (this.user && !this.user.userId && this.user.password !== this.user.passwordAgain) {
                this['$message']({
                    message: '两次密码不一致',
                    type: 'warning'
                });
                return;
            }
            let isOk = CommonService.validForm(this.$refs.userForm);
            if(!isOk){
                return;
            }
            me.$refs['userForm'].validate((valid) => {
                if (valid) {
                    let encrypt = new JSEncrypt();
                    encrypt.setPublicKey(window.sessionStorage.getItem('loginkey'));
                    //console.log(this.user.password)
                    let pass = encrypt.encrypt(this.user.password);
                    //console.log(pass)
                    let params = JSON.parse(JSON.stringify(this.user));
                     if(this.user.credentialsType){
                        this.user.credentialsType = this.user.credentialsType/1;
                    }

                    if (!isUpdateRole && this.user.roleList && this.user.roleList.length > 0) {
                        params['roleId'] = [];
                        for (let role of this.user.roleList) {
                            params['roleId'].push(role.roleId)
                        }
                    }
                    if (!this.user.userId) {
                        params['password'] = this.user.password;
                         Service.addSystemUser(params).then((res) => {
                            if (res.data.succeeded) {
                                this['$message']({
                                    message: '创建成功！',
                                    type: 'success'
                                });
                                this.getFiles();
                                this.addUserVisible = false;
                            } else {
                                this['$message']({
                                    message: res.data.errorMessage,
                                    type: 'error'
                                });
                                return;
                            }
                        })
                    } else {
                        params['password'] = null;
                        Service.updateUserRole(params).then((res) => {
                            if (res.data.succeeded) {
                                this['$message']({
                                    message: '保存成功！',
                                    type: 'success'
                                });
                                this.getFiles();
                                this.addUserVisible = false;
                            } else {
                                this['$message']({
                                    message: res.data.errorMessage,
                                    type: 'error'
                                });
                                return;
                            }
                        })
                    }
                   
                    
                }
            })

        }

        change(val) {
            //console.log(val)
            this.fileForm.roleIds = val.value
        }

        handleSizeChange(val) {
            this.params.pageSize = val;
            this.getFiles();
        };

        searchList() {
            // this.b.page = 0;
            this.params.page = 1;
            this.params.pageSize = 30;
            this.getFiles();
        }

        rowClick(row) {
            //console.log(row)
        }

        // 初始化表格
        getFiles(): void {
            let parms = {
                fullName: this.filters.fullName,
                pageNum: this.params.page,
                pageSize: this.params.pageSize,
            }
            this.isloading = true;
            Service.getUserList(parms).then((res) => {
                if (res.data.succeeded) {
                    //console.log('=================')
                    //console.log(res.data)
                    this.tableData = res.data.data;
                    for (let item of this.tableData) {
                        if(item.sex==1) {
                            item.sex='1'
                        } else {
                            item.sex='0'
                        }
                        if (item.roleList && item.roleList.length > 0) {
                            let roleName = '';
                            for (let item2 of item.roleList) {
                                roleName += `${item2.roleName};`;
                            }
                            this.$set(item, 'roleName', roleName);
                        }
                    }
                    this.total = res.data.totalRecords
                } else {
                    this['$getError'](res.data.errorMessage);
                }
                this.isloading = false;
            })
        };

        // 全选父组件返回数据
        selectAllEvent(checked, records) {
            this.selection = records;
        };
        // 单选父组件返回数据
        selectChangeEvent(checked, records) {
            this.selection = records;
        };

        //角色下拉框数据
        getRoleSelectData(obj): void {
            this.fileForm.roleIds = [];
            let parme = {
               "userId": obj.userId,
                "roleId": obj.roleId 
            }
            Service.updateUserRole(parme).then((res) => {
                this.roleSelect = res.data.data;
                // this.remoteList = [];
                // this.roleSelect.forEach(item => {
                //     this.remoteList.push({
                //         label: item.roleName,
                //         value: item.id
                //     })
                // });
                // if (obj.roleList.length > 0) {
                //     for (let item of obj.roleList) {
                //         this.fileForm.roleIds.push(item.roleId);
                //     }
                // }
                
                this.fileForm.fullName = obj.fullName;
                // this.fileForm.department = obj.department;
                // this.fileForm.business = obj.business;
                this.userId = obj.userId;
                // this.archiveAgentCode = obj.archiveAgentCode;
                // this.fondCode = obj.fondCode;
            })
        };

        //获取用户信息
        // 角色配置弹出框
        updateUserRole(obj, index): void {
            //console.log(obj)
            this.user = {};
            this.user = obj;
            this.userId = obj.userId;
            this.fileVisible = true;
            // this.getRoleSelectData(obj);
            this.fileForm.roleIds = obj.roleId
            this.remoteList=[]
             Service.getRoleListByHeadquartersCode(obj.headquartersCode).then((res)=>{

                    if (res.data.succeeded) {
                        this.remoteList = res.data.data
                        } else {
                            this['$getError'](res.data.errorMessage);
                        }
            })
        }
        getRoleList() {
            Service.getRoleList({}).then((res) => {//角色列表
                     this.remoteList = res.data.data;
                });
        }
        //提交表单
        submitForm(formName, index) {
            this['$refs'][formName]['validate']((valid) => {
                if (valid) {
                    this.user.roleIds = this.fileForm.roleIds;
                    this.user.fullName = this.fileForm.fullName;
                    this.user.department = this.fileForm.department;
                    this.user.business = this.fileForm.business;
                    // this.saveUser(true);
                    let parms = {
                        userId: this.userId,
                        fullName: this.fileForm.fullName,
                        department: this.fileForm.department,
                        // business: this.fileForm.business,
                        roleId: this.fileForm.roleIds,
                        archiveAgentCode: this.archiveAgentCode,
                        fondCode: this.fondCode,
                    }
                    Service.updateUserRole(parms).then((res) => {
                        if (res.data.succeeded) {
                            this['$Suces']('修改成功');
                            this.fileVisible = false;
                            this.getFiles();
                        } else {
                            this['$getError'](res.data.errorMessage);
                        }
                        this.$refs.test.reset()
                    })
                }
            });

        };

        escrowFondOut() {
            this.treeLoading = true;
            Service.getAllFondsTreeData({}).then((res) => {
                this.treeLoading = false;
                if (res.data.succeeded) {
                    this.treeData = res.data.data;
                    this.defaultLeftOpen = [];
                    this.defaultLeftOpen.push(this.leftFondForm.id);
                } else {
                    this['$message']({
                        message: '树节点数据错误！',
                        type: 'error'
                    });
                }
            });
            this.fileVisibleMove1 = true;
        }

        // 远程搜索项目
        remoteMethod(query) {
            if (query !== '' && query != undefined) {
                this.searchLoading = true;
                Service.getKeyName(query).then((res) => {
                    if (res.data.succeeded) {
                        let data = res.data.data;
                        this.searchOptions = data.map(item => {
                            return {value: item.id, label: item.fondName, code: item.fondCode};
                        });
                        setTimeout(() => {
                            this.searchLoading = false;
                            this.searchOptions = this.searchOptions.filter(item => {
                                return item.label.toLowerCase()
                                    .indexOf(query.toLowerCase()) > -1 || item.code.toLowerCase()
                                    .indexOf(query.toLowerCase()) > -1;
                            });
                        }, 200);
                    } else {
                        this['$message']({
                            message: '查询全宗联想错误！',
                            type: 'error'
                        });
                    }
                });

            } else {
                this.searchOptions = [];
            }
        }

        fondClick() {
            this.treeLoading = true;
            Service.getAllFondsTreeData({}).then((res) => {
                if (res.data.succeeded) {
                    this.treeData = res.data.data;
                    this.defaultLeftOpen = [];
                    this.defaultLeftOpen.push(this.leftFondForm.id);
                    this.$nextTick(function () {
                        this['$refs']['treeku']['setCurrentKey'](this.leftFondForm.id);
                    });
                    for (let child of this.searchOptions) {
                        if (child.value == this.leftFondForm.id) {
                            this.treeObj.id = child.value;
                            this.treeObj.fondName = child.label;
                        }
                    }
                    this.treeLoading = false;
                } else {
                    this['$message']({
                        message: '树节点数据错误！',
                        type: 'error'
                    });
                    this.treeLoading = false;
                }
            });
        }

        handleNodeClick1(row) {
            this.treeObj = row;
        }

        getCheckedNodes1() {
            //console.log(this.treeObj)
            this.fileForm.fondsName = this.treeObj.fondName;
            this.fileForm.fondsId = this.treeObj.id;
            this.fileVisibleMove1 = false;
        }

        getCredentialsTypeCandidates(){
            Service.getCredentialsTypeCandidates({}).then((res)=>{
                if(res.data.succeeded){
                    this.credentialsTypeList = res.data.data;
                }
            })
        }

        // treeselect 用于规范化源数据
        normalizer(node) {
            return {
                id: node.fondCode,
                label: node.fondName,
                children: node.children ? node.children : undefined,
            }
        }

        treeselectInput() {
//            if (!this.treeselectFondCode) {
//                this.fondCode = localStorage.getItem("LogonFondCode");
//            }
        }

        // treeselect
        treeselect(node, instanceId) {
            //console.log(node, instanceId);
//            this.treeselectFondCode = node.fondCode;
        }

        getTree() {
            Service.getTree({}).then(res => {
                if (res.data.succeeded) {
                    this.fonddata = res.data.data;
                    //console.log(this.fonddata)
//                    this.treeselectFondCode = [res.data.data[0].fondCode];
                    this.returnCompany(this.fonddata);
                } else {
//                    this.getError(res.data.errorMessage)
                }
            });
        }

        //递归公司
        returnCompany(data) {
            for (var item of data) {
                item.fondName = '[ ' + item.fondCode + ' ]' + item.fondName;
                if (item.children != null) {
                    this.returnCompany(item.children)
                }
            }
        }
        resizeEvent(){
        // this.windowHeight = document.documentElement.clientHeight;
        this.height = this.windowHeight - 210;
    }
        created() {
            // this.$refs.test.reset();
            // this.getCredentialsTypeCandidates();
            // this.getTree();
            this.userInfoForm = JSON.parse(window.sessionStorage.getItem('userInfoForm'))
            this.formName = JSON.parse(window.localStorage.getItem('headquartersCode'))
            this.getFiles();
            this.resizeEvent();
            this.getRoleList()
        }

        mounted() {
            window.onresize = () => {
                return (() => {
                    this.bodyHeight = document.documentElement.clientHeight - 225;
                })()
            };
        };

    };


</script>

<style lang="scss" scoped>
    // @import '../../../styles/system/userManagement/userManagement.scss';
    /deep/ .el-button + .el-button{
        margin-left: 0 !important;
    }
    /deep/ .el-button--mini, .el-button--mini.is-round {
        padding: 7px !important;
    }
</style>